//
//  DMQRScannerViewController.swift
//  DigitalMuseum
//
//  Created by zhongshan on 2024/2/21.
//

import UIKit
import FDFullscreenPopGesture
import SnapKit

class DMQRScannerViewController: UIViewController {
    
    private let scannerView: DMScannerView = DMScannerView()
    private let animationView: DMScannerAnimationView = DMScannerAnimationView()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        scannerView.start()
    }
    
    private func setupUI() {
        view.backgroundColor = .white
        fd_prefersNavigationBarHidden = true
        
        scannerView.delegate = self
        view.addSubview(scannerView)
        scannerView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        view.addSubview(animationView)
        animationView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        let titleLabel = UILabel()
        titleLabel.font = .systemFont(ofSize: 16, weight: .semibold)
        titleLabel.textColor = .white
        titleLabel.text = "扫一扫"
        view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top).offset(12)
        }
        
        let backButton = UIButton(type: .custom)
        backButton.setImage(UIImage(resource: .scannerBack), for: .normal)
        backButton.addTarget(self, action: #selector(handleBackButtonClick), for: .touchUpInside)
        view.addSubview(backButton)
        backButton.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.centerY.equalTo(titleLabel);
            make.height.width.equalTo(50)
        }
    }
    
    @objc 
    private func handleBackButtonClick() {
        navigationController?.popViewController(animated: true)
    }
}

// MARK: - DMScannerViewDelegate
extension DMQRScannerViewController: DMScannerViewDelegate {
    
    func scannerView(_ scannerView: DMScannerView, didScanOutResults results: [DMScanResult]) {
        
    }
    
    func scannerView(_ scannerView: DMScannerView, didChooseResult result: DMScanResult) {
        print(result.content)
    }
    
    func scannerViewDidStartRunning(_ scannerView: DMScannerView) {
        animationView.startAnimation()
    }
    
    func scannerViewDidStopRunning(_ scannerView: DMScannerView) {
        animationView.stopAnimation()
    }
}
